// ==UserScript==
// @name         Greasy Fork脚本搜索助手-电脑端
// @namespace    http://tampermonkey.net/
// @version      4.1
// @description  [电脑端专用] 右侧悬浮按钮+智能域名+镜像站支持+后台设置+按钮开关+远程配置+修复灰色输入框问题
// @author       DeepSeek+Cursor
// @match        *://*/*
// @license      MIT
// @grant        GM_registerMenuCommand
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @connect      gitee.com
// @connect      raw.githubusercontent.com
// @run-at       document-end
// @icon        https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/Greasy%20Fork%E8%84%9A%E6%9C%AC%E6%90%9C%E7%B4%A2%E5%8A%A9%E6%89%8B/Greasy%20Fork-icon.png
// @updateURL https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/Greasy%20Fork%E8%84%9A%E6%9C%AC%E6%90%9C%E7%B4%A2%E5%8A%A9%E6%89%8B/Greasy%20Fork%E8%84%9A%E6%9C%AC%E6%90%9C%E7%B4%A2%E5%8A%A9%E6%89%8B-%E7%94%B5%E8%84%91%E7%AB%AF.user.js
// @noframes
// ==/UserScript==

(function() {
    'use strict';

    // 远程配置文件URL（可以替换为您自己的Gitee仓库地址）
    const REMOTE_CONFIG_URL = 'https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/Greasy%20Fork%E8%84%9A%E6%9C%AC%E6%90%9C%E7%B4%A2%E5%8A%A9%E6%89%8B/%E9%95%9C%E5%83%8F%E7%AB%99%E8%BF%9C%E7%A8%8B%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6.js';

    // 配置项 (用户可自定义部分)
    const defaultConfig = {
        baseUrl: 'https://greasyfork.org/zh-CN',  // 默认使用镜像站地址
        queryBaseUrl: 'https://cdn-sg-dev-static.greasyfork.org.cn', // 查询类型镜像站地址
        scriptcatUrl: 'https://scriptcat.org/zh-CN', // scriptcat脚本猫地址
        buttonIcon: '🔍',                          // 搜索图标
        buttonColor: '#00BCD4',                   // 青色主题色
        hoverDelay: 2000,                         // 自动隐藏延迟(毫秒)
        initialDelay: 1500,                       // 初始显示时间(毫秒)
        showButton: true,                         // 是否显示搜索按钮
        useRemoteConfig: true,                    // 是否使用远程配置
        lastRemoteUpdate: 0,                      // 上次远程更新时间
        searchUrlType: 'path'                     // 搜索URL类型: 'path' 或 'query'
    };
    
    // 从存储中获取配置，如果不存在则使用默认配置
    let config = GM_getValue('gfSearchConfig', defaultConfig);
    
    // 确保所有配置项都存在且有效
    for (const key in defaultConfig) {
        if (config[key] === undefined || config[key] === null) {
            config[key] = defaultConfig[key];
        }
    }

    // 保存配置到存储
    const saveConfig = () => {
        GM_setValue('gfSearchConfig', config);
        console.log('配置已保存:', config);
    };
    
    // 从远程加载配置
    const loadRemoteConfig = () => {
        return new Promise((resolve, reject) => {
            if (!config.useRemoteConfig) {
                resolve(false);
                return;
            }
            
            const now = Date.now();
            const updateInterval = 24 * 60 * 60 * 1000;
            
            if (now - config.lastRemoteUpdate < updateInterval && config.lastRemoteUpdate !== 0) {
                console.log('配置未过期，跳过更新');
                resolve(false);
                return;
            }
            
            console.log('开始获取远程配置...');
            GM_xmlhttpRequest({
                method: 'GET',
                url: REMOTE_CONFIG_URL,
                timeout: 5000,
                onload: (response) => {
                    if (response.status === 200) {
                        try {
                            const remoteConfigText = response.responseText;
                            console.log('获取到远程配置:', remoteConfigText);
                            
                            // 修改正则表达式以匹配更灵活的配置格式
                            const configMatch = remoteConfigText.match(/const\s+remoteConfig\s*=\s*({[\s\S]*?});/);
                            
                            if (configMatch && configMatch[1]) {
                                // 使用更安全的解析方式
                                let remoteConfig;
                                try {
                                    remoteConfig = Function('return ' + configMatch[1])();
                                } catch (e) {
                                    // 如果直接解析失败，尝试提取JSON部分
                                    const jsonMatch = configMatch[1].match(/{[\s\S]*}/);
                                    if (jsonMatch) {
                                        remoteConfig = JSON.parse(jsonMatch[0]);
                                    } else {
                                        throw new Error('无法解析远程配置格式');
                                    }
                                }
                                
                                console.log('解析后的远程配置:', remoteConfig);
                                
                                let configChanged = false;
                                
                                // 检查并更新每个配置项，使用更严格的类型检查
                                if (remoteConfig.baseUrl && typeof remoteConfig.baseUrl === 'string') {
                                    const newBaseUrl = remoteConfig.baseUrl.trim();
                                    if (newBaseUrl && newBaseUrl !== config.baseUrl) {
                                        console.log('更新baseUrl:', config.baseUrl, '->', newBaseUrl);
                                        config.baseUrl = newBaseUrl;
                                        configChanged = true;
                                    }
                                }
                                
                                if (remoteConfig.queryBaseUrl && typeof remoteConfig.queryBaseUrl === 'string') {
                                    const newQueryBaseUrl = remoteConfig.queryBaseUrl.trim();
                                    if (newQueryBaseUrl && newQueryBaseUrl !== config.queryBaseUrl) {
                                        console.log('更新queryBaseUrl:', config.queryBaseUrl, '->', newQueryBaseUrl);
                                        config.queryBaseUrl = newQueryBaseUrl;
                                        configChanged = true;
                                    }
                                }
                                
                                if (remoteConfig.scriptcatUrl && typeof remoteConfig.scriptcatUrl === 'string') {
                                    const newScriptcatUrl = remoteConfig.scriptcatUrl.trim();
                                    if (newScriptcatUrl && newScriptcatUrl !== config.scriptcatUrl) {
                                        console.log('更新scriptcatUrl:', config.scriptcatUrl, '->', newScriptcatUrl);
                                        config.scriptcatUrl = newScriptcatUrl;
                                        configChanged = true;
                                    }
                                }
                                
                                if (remoteConfig.searchUrlType && typeof remoteConfig.searchUrlType === 'string') {
                                    const newSearchUrlType = remoteConfig.searchUrlType.trim().toLowerCase();
                                    if (['path', 'query', 'scriptcat'].includes(newSearchUrlType) && newSearchUrlType !== config.searchUrlType) {
                                        console.log('更新searchUrlType:', config.searchUrlType, '->', newSearchUrlType);
                                        config.searchUrlType = newSearchUrlType;
                                        configChanged = true;
                                    }
                                }
                                
                                if (configChanged) {
                                    console.log('配置已更新，保存新配置');
                                    config.lastRemoteUpdate = now;
                                    saveConfig();
                                    
                                    // 立即更新UI
                                    console.log('更新UI显示');
                                    const searchBtn = document.getElementById('scriptSearchBtn');
                                    if (searchBtn) {
                                        searchBtn.style.backgroundColor = config.buttonColor;
                                    }
                                    
                                    GM_addStyle(`
                                        #scriptSearchBtn {
                                            background: ${config.buttonColor};
                                        }
                                        #scriptSearchBtn:hover {
                                            box-shadow: 0 6px 16px ${config.buttonColor}40;
                                        }
                                    `);
                                    
                                    // 更新设置面板中的显示
                                    const baseUrlInput = document.getElementById('baseUrl');
                                    if (baseUrlInput) {
                                        baseUrlInput.value = config.baseUrl;
                                    }
                                    
                                    const urlTypeRadios = document.querySelectorAll('input[name="searchUrlType"]');
                                    urlTypeRadios.forEach(radio => {
                                        if (radio.value === config.searchUrlType) {
                                            radio.checked = true;
                                        }
                                    });
                                    
                                    const urlTypeText = document.querySelector('div > div > strong');
                                    if (urlTypeText) {
                                        if (config.searchUrlType === 'scriptcat') {
                                            urlTypeText.textContent = 'ScriptCat类型';
                                        } else if (config.searchUrlType === 'query') {
                                            urlTypeText.textContent = '查询类型';
                                        } else {
                                            urlTypeText.textContent = '路径类型';
                                        }
                                    }
                                }
                                
                                resolve(configChanged);
                            } else {
                                console.error('无法解析远程配置');
                                reject(new Error('无法解析远程配置'));
                            }
                        } catch (error) {
                            console.error('解析远程配置失败:', error);
                            reject(error);
                        }
                    } else {
                        console.error('远程配置加载失败:', response.status);
                        reject(new Error('远程配置加载失败: ' + response.status));
                    }
                },
                onerror: (error) => {
                    console.error('远程配置请求失败:', error);
                    reject(error);
                },
                ontimeout: () => {
                    console.error('远程配置请求超时');
                    reject(new Error('远程配置加载超时'));
                }
            });
        });
    };

    // 悬浮按钮样式 (电脑端专用)
    GM_addStyle(`
        #scriptSearchBtn {
            position: fixed;
            right: 0;
            bottom: 25px;
            z-index: 2147483647;
            width: 55px;
            height: 55px;
            border-radius: 50% 0 0 50%;
            background: ${config.buttonColor};
            color: white;
            border: none;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,188,212,0.3);
            font-size: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            transform: translateX(0);
        }
        #scriptSearchBtn.collapsed {
            transform: translateX(40px);
        }
        #scriptSearchBtn:hover {
            transform: translateX(0) scale(1.15);
            box-shadow: 0 6px 16px rgba(0,188,212,0.4);
        }
        #scriptSearchBtn.collapsed:hover {
            transform: translateX(0);
        }
        #gfSearchModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 25px 30px;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.3);
            z-index: 2147483648;
            width: 420px;
            max-width: 90vw;
            max-height: 85vh;
            overflow-y: auto;
            font-size: 15px;
            font-family: Arial, sans-serif;
        }
        #gfSearchModal .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            position: relative;
        }
        #gfSearchModal .modal-header h3 {
            margin: 0;
            color: ${config.buttonColor};
            font-size: 20px;
            flex-grow: 1;
            text-align: center;
        }
        #gfSearchModal .close-btn {
            position: absolute;
            right: 0;
            top: 0;
            background: none;
            border: none;
            font-size: 22px;
            cursor: pointer;
            color: #999;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.2s;
        }
        #gfSearchModal .close-btn:hover {
            background: #f0f0f0;
            color: #333;
        }
        #gfSearchModal label {
            display: block;
            margin: 15px 0 8px;
            font-weight: bold;
        }
        #gfSearchModal input[type="text"], 
        #gfSearchModal input[type="color"],
        #gfSearchModal input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            margin-bottom: 8px;
            box-sizing: border-box;
            font-size: 15px;
        }
        #gfSearchModal .switch-container {
            display: flex;
            align-items: center;
            margin: 20px 0;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 8px;
            border-left: 5px solid ${config.buttonColor};
        }
        #gfSearchModal .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 30px;
            margin-right: 15px;
        }
        #gfSearchModal .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        #gfSearchModal .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 30px;
        }
        #gfSearchModal .slider:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        #gfSearchModal input:checked + .slider {
            background-color: ${config.buttonColor};
        }
        #gfSearchModal input:checked + .slider:before {
            transform: translateX(30px);
        }
        #gfSearchModal .button-group {
            display: flex;
            justify-content: center;
            margin-top: 25px;
        }
        #gfSearchModal button.save-btn {
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            background: ${config.buttonColor};
            color: white;
            font-weight: bold;
            font-size: 16px;
            transition: all 0.2s;
            min-width: 150px;
        }
        #gfSearchModal button.save-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        #gfSearchModal .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2147483647;
        }
        #gfSearchModal .section-title {
            border-bottom: 2px solid #eee;
            padding-bottom: 8px;
            margin-top: 20px;
            color: ${config.buttonColor};
            font-size: 18px;
            font-weight: bold;
        }
        #gfSearchModal .color-preview {
            display: inline-block;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            margin-left: 10px;
            vertical-align: middle;
            border: 1px solid #ddd;
        }
        #gfSearchModal .remote-info {
            margin-top: 10px;
            font-size: 13px;
            color: #666;
        }
        #gfSearchModal .remote-status {
            padding: 5px 10px;
            border-radius: 4px;
            background: #f0f0f0;
            display: inline-block;
            margin-top: 5px;
        }
        #gfSearchModal .remote-status.success {
            background: #e8f5e9;
            color: #2e7d32;
        }
        #gfSearchModal .remote-status.error {
            background: #ffebee;
            color: #c62828;
        }
        #gfSearchModal .remote-status.warning {
            background: #fff8e1;
            color: #ff8f00;
        }
    `);

    // 智能域名处理 (强化去前缀逻辑)
    const getCleanDomain = (hostname) => {
        // 处理IP地址
        if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) return hostname;

        // 分步处理
        return hostname
            .replace(/^([a-z]+\.)*?(www\d*|m|mobile|web|wap)\./i, '')  // 移除所有前缀
            .split('.')
            .slice(-2)    // 取最后两部分
            .join('.')
            .replace(/\.$/, '');  // 防止空字符
    };

    // 创建按钮 (电脑端优化)
    const createButton = () => {
        const btn = document.createElement('button');
        btn.id = 'scriptSearchBtn';
        btn.title = '点击搜索本站脚本 (' + getCleanDomain(location.hostname) + ')';
        btn.textContent = config.buttonIcon;
        
        // 鼠标事件处理
        let timeout;
        
        btn.addEventListener('mouseenter', () => {
            clearTimeout(timeout);
            btn.classList.remove('collapsed');
        });
        
        btn.addEventListener('mouseleave', () => {
            timeout = setTimeout(() => {
                btn.classList.add('collapsed');
            }, config.hoverDelay);
        });
        
        // 点击执行搜索
        btn.addEventListener('click', startSearch);

        // 初始状态设置为显示，然后自动折叠
        setTimeout(() => {
            btn.classList.add('collapsed');
        }, config.initialDelay);
        
        return btn;
    };

    // 执行搜索
    const startSearch = () => {
        const domain = getCleanDomain(location.hostname);
        const urlType = config.searchUrlType || defaultConfig.searchUrlType;
        
        // 根据URL类型选择合适的基础URL
        let actualBaseUrl;
        if (urlType === 'query') {
            actualBaseUrl = config.queryBaseUrl || defaultConfig.queryBaseUrl;
        } else if (urlType === 'scriptcat') {
            actualBaseUrl = config.scriptcatUrl || defaultConfig.scriptcatUrl;
        } else {
            actualBaseUrl = config.baseUrl || defaultConfig.baseUrl;
        }
        
        // 移除末尾斜杠以保持一致性
        if (actualBaseUrl.endsWith('/')) {
            actualBaseUrl = actualBaseUrl.slice(0, -1);
        }
        
        // 添加详细的调试日志
        console.log('=============== 搜索调试信息 ===============');
        console.log('当前域名:', location.hostname);
        console.log('清理后域名:', domain);
        console.log('URL类型设置:', urlType);
        console.log('远程配置开启状态:', config.useRemoteConfig ? '已开启' : '已关闭');
        console.log('配置信息:', JSON.stringify(config, null, 2));
        console.log('使用的基础URL:', actualBaseUrl);
        
        // 构建搜索URL
        let searchUrl;
        if (urlType === 'query') {
            searchUrl = `${actualBaseUrl}/s?q=${encodeURIComponent(domain)}`;
            console.log('使用查询类型URL格式');
        } else if (urlType === 'scriptcat') {
            searchUrl = `${actualBaseUrl}/search?keyword=${encodeURIComponent(domain)}`;
            console.log('使用ScriptCat类型URL格式');
        } else {
            console.log('使用路径类型URL格式');
            searchUrl = `${actualBaseUrl}/scripts/by-site/${encodeURIComponent(domain)}`;
        }
        
        console.log('最终搜索URL:', searchUrl);
        console.log('============================================');
        
        window.open(searchUrl, '_blank');
    };
    
    // 切换按钮显示状态
    const toggleButtonVisibility = () => {
        config.showButton = !config.showButton;
        saveConfig();
        
        // 显示操作结果
        const status = config.showButton ? '已开启' : '已关闭';
        
        // 创建临时提示
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            bottom: 80px;
            right: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 2147483647;
            font-size: 14px;
        `;
        toast.textContent = `搜索按钮${status}，刷新页面生效`;
        document.body.appendChild(toast);
        
        // 3秒后移除提示
        setTimeout(() => {
            toast.remove();
        }, 3000);
        
        // 实时移除或添加按钮
        if (!config.showButton) {
            const existingButton = document.getElementById('scriptSearchBtn');
            if (existingButton) {
                existingButton.remove();
            }
        } else {
            // 如果按钮不存在且需要显示，则添加按钮
            if (!document.getElementById('scriptSearchBtn')) {
                const btn = createButton();
                document.body.appendChild(btn);
            }
        }
        
        // 更新菜单命令
        // 由于无法直接更新菜单命令文本，我们可以移除和重新添加
        GM_registerMenuCommand(config.showButton ? '❌ 关闭搜索按钮' : '✅ 开启搜索按钮', toggleButtonVisibility);
    };
    
    // 格式化日期
    const formatDate = (timestamp) => {
        if (!timestamp) return '从未更新';
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    };
    
    // 手动更新远程配置
    const updateRemoteConfig = async () => {
        const statusElement = document.getElementById('remoteStatus');
        if (statusElement) {
            statusElement.textContent = '正在更新...';
            statusElement.className = 'remote-status warning';
        }
        
        try {
            // 清除本地配置缓存
            GM_setValue('gfSearchConfig', null);
            console.log('已清除本地配置缓存');
            
            // 重置配置为默认值
            config = { ...defaultConfig };
            console.log('已重置为默认配置');
            
            // 强制更新远程配置
            config.lastRemoteUpdate = 0;
            
            const updated = await loadRemoteConfig();
            
            if (statusElement) {
                if (updated) {
                    statusElement.textContent = '更新成功，3秒后刷新页面...';
                    statusElement.className = 'remote-status success';
                    
                    // 更新镜像站地址输入框
                    const baseUrlInput = document.getElementById('baseUrl');
                    if (baseUrlInput) {
                        baseUrlInput.value = config.baseUrl;
                    }
                    
                    // 更新URL类型单选按钮
                    const urlTypeRadios = document.querySelectorAll('input[name="searchUrlType"]');
                    urlTypeRadios.forEach(radio => {
                        if (radio.value === config.searchUrlType) {
                            radio.checked = true;
                        }
                    });
                    
                    // 更新URL类型显示文本
                    const urlTypeText = document.querySelector('div > div > strong');
                    if (urlTypeText) {
                        if (config.searchUrlType === 'scriptcat') {
                            urlTypeText.textContent = 'ScriptCat类型';
                        } else if (config.searchUrlType === 'query') {
                            urlTypeText.textContent = '查询类型';
                        } else {
                            urlTypeText.textContent = '路径类型';
                        }
                    }
                    
                    // 更新最后更新时间
                    const lastUpdateElement = document.getElementById('lastUpdate');
                    if (lastUpdateElement) {
                        lastUpdateElement.textContent = formatDate(config.lastRemoteUpdate);
                    }

                    // 保存新配置
                    saveConfig();
                    console.log('已保存新配置:', config);

                    // 3秒后自动刷新页面
                    setTimeout(() => {
                        location.reload();
                    }, 3000);
                } else {
                    statusElement.textContent = '无需更新';
                    statusElement.className = 'remote-status';
                }
            }
        } catch (error) {
            if (statusElement) {
                statusElement.textContent = '更新失败: ' + error.message;
                statusElement.className = 'remote-status error';
            }
            console.error('更新失败:', error);
        }
    };
    
    // 创建设置面板
    const createSettingsModal = () => {
        // 移除已有的设置面板
        const existingModal = document.getElementById('gfSearchModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 创建背景遮罩
        const backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop';
        document.body.appendChild(backdrop);
        
        // 创建设置面板
        const modal = document.createElement('div');
        modal.id = 'gfSearchModal';
        
        modal.innerHTML = `
            <div class="modal-header">
                <h3>Greasy Fork脚本搜索助手设置</h3>
                <button class="close-btn" title="关闭">✕</button>
            </div>
            
            <div class="section-title">搜索按钮控制</div>
            <div class="switch-container">
                <label class="switch">
                    <input type="checkbox" id="showButton" ${config.showButton ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
                <div>
                    <strong>显示搜索按钮</strong>
                    <div style="color: #666; font-size: 14px; margin-top: 5px;">
                        ${config.showButton ? '当前状态：已开启' : '当前状态：已关闭'}
                    </div>
                </div>
            </div>
            
            <div class="section-title">镜像站设置</div>
            <div class="switch-container">
                <label class="switch">
                    <input type="checkbox" id="useRemoteConfig" ${config.useRemoteConfig ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
                <div>
                    <strong>使用远程镜像站配置</strong>
                    <div style="color: #666; font-size: 14px; margin-top: 5px;">
                        ${config.useRemoteConfig ? '当前状态：已开启' : '当前状态：已关闭'}
                    </div>
                </div>
            </div>
            
            <div class="remote-info">
                <div>远程配置地址: <span style="color:#888; font-size:12px;">${REMOTE_CONFIG_URL}</span></div>
                <div>最后更新时间: <span id="lastUpdate">${formatDate(config.lastRemoteUpdate)}</span></div>
                <div>
                    <button id="updateRemote" style="padding:5px 10px; margin-top:5px; background:${config.buttonColor}; color:white; border:none; border-radius:4px; cursor:pointer;">
                        立即更新
                    </button>
                    <span id="remoteStatus" class="remote-status">-</span>
                </div>
            </div>
            
            <label for="baseUrl">镜像站地址:</label>
            <input type="text" id="baseUrl" value="${config.baseUrl}" placeholder="例如: https://gf.qytechs.cn/zh-CN" ${config.useRemoteConfig ? 'readonly' : ''}>
            <div id="baseUrlHint" style="font-size: 12px; color: #666; margin-top: 5px; ${config.useRemoteConfig ? '' : 'display: none;'}">
                启用远程配置后，镜像站地址由远程配置控制，如需自定义请关闭远程配置
            </div>
            
            <div class="section-title">URL类型设置</div>
            <div>
                <label style="display: inline-flex; align-items: center; margin-right: 15px;">
                    <input type="radio" name="searchUrlType" value="path" ${(config.searchUrlType === 'path' || !config.searchUrlType) ? 'checked' : ''} ${config.useRemoteConfig ? 'disabled' : ''}>
                    <span style="margin-left: 8px;">路径类型</span>
                </label>
                <label style="display: inline-flex; align-items: center; margin-right: 15px;">
                    <input type="radio" name="searchUrlType" value="query" ${config.searchUrlType === 'query' ? 'checked' : ''} ${config.useRemoteConfig ? 'disabled' : ''}>
                    <span style="margin-left: 8px;">查询类型</span>
                </label>
                <label style="display: inline-flex; align-items: center;">
                    <input type="radio" name="searchUrlType" value="scriptcat" ${config.searchUrlType === 'scriptcat' ? 'checked' : ''} ${config.useRemoteConfig ? 'disabled' : ''}>
                    <span style="margin-left: 8px;">ScriptCat</span>
                </label>
            </div>
            <div style="font-size: 12px; color: #666; margin-top: 5px; ${config.useRemoteConfig ? '' : 'display: none;'}" id="urlTypeHint">
                启用远程配置后，URL类型由远程配置控制
            </div>
            <div style="font-size: 12px; color: #333; margin-top: 5px;">
                <div>当前使用: <strong>${config.searchUrlType === 'scriptcat' ? 'ScriptCat类型' : (config.searchUrlType === 'query') ? '查询类型' : '路径类型'}</strong></div>
                <div>- 路径类型URL示例: <span style="color:#0056b3; font-family: monospace; font-size: 11px;">https://gf.qytechs.cn/zh-CN/scripts/by-site/baidu.com</span></div>
                <div>- 查询类型URL示例: <span style="color:#0056b3; font-family: monospace; font-size: 11px;">https://cdn-sg-dev-static.greasyfork.org.cn/s?q=baidu.com</span></div>
                <div>- ScriptCat类型URL示例: <span style="color:#0056b3; font-family: monospace; font-size: 11px;">https://scriptcat.org/zh-CN/search?keyword=baidu.com</span></div>
                <div style="color:#d32f2f; margin-top: 8px; font-size: 11px;">* 注意: 查询类型将固定使用cdn-sg-dev-static.greasyfork.org.cn作为域名</div>
                <div style="color:#d32f2f; font-size: 11px;">* 注意: ScriptCat类型将固定使用scriptcat.org作为域名</div>
            </div>
            
            <div class="section-title">按钮外观</div>
            <label for="buttonIcon">搜索图标:</label>
            <input type="text" id="buttonIcon" value="${config.buttonIcon}" placeholder="例如: 🔍 📝 🔎">
            
            <label for="buttonColor">按钮颜色: <span class="color-preview" style="background-color: ${config.buttonColor}"></span></label>
            <input type="color" id="buttonColor" value="${config.buttonColor}">
            
            <div class="section-title">动画设置</div>
            <label for="hoverDelay">自动隐藏延迟(毫秒):</label>
            <input type="number" id="hoverDelay" value="${config.hoverDelay}" min="500" max="10000" step="100">
            
            <label for="initialDelay">初始显示时间(毫秒):</label>
            <input type="number" id="initialDelay" value="${config.initialDelay}" min="500" max="10000" step="100">
            
            <div class="button-group">
                <button class="save-btn" id="saveSettings">保存设置</button>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 添加颜色预览功能
        const colorInput = document.getElementById('buttonColor');
        const colorPreview = modal.querySelector('.color-preview');
        
        colorInput.addEventListener('input', () => {
            colorPreview.style.backgroundColor = colorInput.value;
        });
        
        // 远程配置开关事件
        const useRemoteConfigCheckbox = document.getElementById('useRemoteConfig');
        const baseUrlInput = document.getElementById('baseUrl');
        const baseUrlHint = document.getElementById('baseUrlHint');
        const urlTypeRadios = document.querySelectorAll('input[name="searchUrlType"]');
        const urlTypeHint = document.getElementById('urlTypeHint');
        
        // 初始化输入框样式
        if (config.useRemoteConfig) {
            baseUrlInput.style.opacity = '0.7';
            baseUrlInput.style.backgroundColor = '#f5f5f5';
            urlTypeRadios.forEach(radio => {
                radio.disabled = true;
                radio.parentNode.style.opacity = '0.7';
            });
        }
        
        useRemoteConfigCheckbox.addEventListener('change', () => {
            baseUrlInput.readOnly = useRemoteConfigCheckbox.checked;
            baseUrlInput.style.opacity = useRemoteConfigCheckbox.checked ? '0.7' : '1';
            baseUrlInput.style.backgroundColor = useRemoteConfigCheckbox.checked ? '#f5f5f5' : '';
            baseUrlHint.style.display = useRemoteConfigCheckbox.checked ? '' : 'none';
            
            // 启用或禁用URL类型单选按钮
            urlTypeRadios.forEach(radio => {
                radio.disabled = useRemoteConfigCheckbox.checked;
                radio.parentNode.style.opacity = useRemoteConfigCheckbox.checked ? '0.7' : '1';
            });
            urlTypeHint.style.display = useRemoteConfigCheckbox.checked ? '' : 'none';
        });
        
        // 更新按钮事件
        document.getElementById('updateRemote').addEventListener('click', updateRemoteConfig);
        
        // 绑定保存事件
        document.getElementById('saveSettings').addEventListener('click', () => {
            config.baseUrl = document.getElementById('baseUrl').value;
            config.buttonIcon = document.getElementById('buttonIcon').value;
            config.buttonColor = document.getElementById('buttonColor').value;
            config.hoverDelay = parseInt(document.getElementById('hoverDelay').value);
            config.initialDelay = parseInt(document.getElementById('initialDelay').value);
            config.showButton = document.getElementById('showButton').checked;
            config.useRemoteConfig = document.getElementById('useRemoteConfig').checked;
            
            // 保存URL类型设置（仅当未使用远程配置时）
            if (!config.useRemoteConfig) {
                const selectedUrlType = document.querySelector('input[name="searchUrlType"]:checked');
                if (selectedUrlType) {
                    config.searchUrlType = selectedUrlType.value;
                }
            }
            
            saveConfig();
            closeSettingsModal();
            
            // 显示操作结果
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                bottom: 80px;
                right: 20px;
                background: rgba(0,0,0,0.7);
                color: white;
                padding: 10px 20px;
                border-radius: 4px;
                z-index: 2147483647;
                font-size: 14px;
            `;
            toast.textContent = '设置已保存，刷新页面生效';
            document.body.appendChild(toast);
            
            // 3秒后移除提示
            setTimeout(() => {
                toast.remove();
                location.reload();
            }, 2000);
        });
        
        // 绑定关闭按钮事件
        modal.querySelector('.close-btn').addEventListener('click', closeSettingsModal);
        backdrop.addEventListener('click', closeSettingsModal);
    };
    
    // 关闭设置面板
    const closeSettingsModal = () => {
        const modal = document.getElementById('gfSearchModal');
        const backdrop = document.querySelector('.modal-backdrop');
        
        if (modal) modal.remove();
        if (backdrop) backdrop.remove();
    };

    // 确保baseUrl是有效的URL
    const ensureValidBaseUrl = () => {
        // 检查URL是否有效格式，如果无效则使用默认地址
        if (!config.baseUrl || config.baseUrl.trim() === '') {
            console.log('检测到空URL，使用默认地址');
            config.baseUrl = defaultConfig.baseUrl;
            return true;
        }
        
        try {
            new URL(config.baseUrl);
        } catch (e) {
            console.log('检测到无效URL格式，使用默认地址');
            config.baseUrl = defaultConfig.baseUrl;
            return true;
        }
        
        return false; // 没有进行修改
    };
    
    // 重置所有配置
    const resetAllConfig = () => {
        // 获取当前按钮显示状态
        const prevShowButton = config.showButton;
        
        // 恢复默认配置
        config = {...defaultConfig};
        
        // 保存配置
        saveConfig();
        
        // 立即应用按钮显示/隐藏状态的更改
        if (prevShowButton !== config.showButton) {
            const existingBtn = document.getElementById('scriptSearchBtn');
            if (config.showButton) {
                // 如果开启按钮但不存在，则创建
                if (!existingBtn) {
                    const btn = createButton();
                    document.body.appendChild(btn);
                }
            } else {
                // 如果关闭按钮且存在，则移除
                if (existingBtn) {
                    existingBtn.remove();
                }
            }
        }
        
        // 显示操作结果
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            bottom: 80px;
            right: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 2147483647;
            font-size: 14px;
        `;
        toast.textContent = '已重置所有设置，按钮状态已立即生效';
        document.body.appendChild(toast);
        
        // 3秒后刷新页面（刷新菜单项文本需要）
        setTimeout(() => {
            toast.remove();
            location.reload();
        }, 2000);
    };

    // 初始化
    (async function init() {
        console.log('=============== 脚本初始化 ===============');
        console.log('初始配置:', JSON.stringify(config, null, 2));
        
        // 确保baseUrl有效
        if (ensureValidBaseUrl()) {
            console.log('已修正baseUrl:', config.baseUrl);
            saveConfig();
        }
        
        // 重置上次更新时间以强制加载远程配置（确保总是尝试获取最新配置）
        if (config.useRemoteConfig) {
            console.log('远程配置已启用，重置上次更新时间以强制获取最新配置');
            config.lastRemoteUpdate = 0;
            saveConfig();
        } else {
            console.log('远程配置已禁用，使用本地配置');
        }
        
        // 尝试加载远程配置
        try {
            console.log('正在加载远程配置...');
            const updated = await loadRemoteConfig();
            if (updated) {
                console.log('远程配置加载成功！新配置:', JSON.stringify(config, null, 2));
                console.log('URL类型设置为:', config.searchUrlType);
                console.log('基础URL设置为:', config.baseUrl);
                console.log('查询类型URL设置为:', config.queryBaseUrl);
            } else {
                console.log('远程配置未更新，使用现有配置:', JSON.stringify(config, null, 2));
            }
        } catch (error) {
            console.error('远程配置加载失败:', error);
        }
        
        // 添加悬浮按钮（如果启用）
        if (config.showButton) {
            const btn = createButton();
            document.body.appendChild(btn);
        }

        // 注册菜单命令
        GM_registerMenuCommand('🔍 搜索 ' + getCleanDomain(location.hostname) + ' 脚本', startSearch);
        GM_registerMenuCommand('⚙️ 设置', createSettingsModal);
        GM_registerMenuCommand(config.showButton ? '❌ 关闭搜索按钮' : '✅ 开启搜索按钮', toggleButtonVisibility);
        GM_registerMenuCommand('🔄 重置所有配置', resetAllConfig);
        
        console.log('=============== 初始化完成 ===============');
    })();
})(); 